import md5 from 'crypto-js/md5';

export const useLock = () => {
    const lockContext = new Map();
    /**
     * 获取锁
     */
    const getLock = (value) => {
        if (value.code) {
            value.code = undefined;
            // value.delete('code')
        }
        const hash = md5(JSON.stringify(value)).toString();
        if (hasLock(hash)) {
            return false;
        }
        lockContext.set(hash, value);
        return hasLock(hash) ? hash : false;
    };
    /**
     * 释放锁
     */
    const unLock = (value) => {
        if (typeof value === 'string') {
            lockContext.delete(value);
            return true;
        } else {
            if (value.code) {
                value.code = undefined;
                // value.delete('code')
            }
            const hash = md5(JSON.stringify(value)).toString();
            return lockContext.delete(hash);
        }
    };
    /**
     * 检查锁
     */
    const hasLock = (hash) => {
        return lockContext.has(hash);
    };

    return {
        getLock,
        unLock,
        hasLock
    };
};
